package cn.wzc.crystal.platform.curd;

import cn.wzc.crystal.platform.golbal.GlobalErrorCode;
import cn.wzc.crystal.platform.query.QueryPageResult;
import cn.wzc.crystal.platform.support.AbstractEntity;
import cn.wzc.crystal.platform.support.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

public abstract class AbstractCrudController<Dto extends Serializable, Entity extends AbstractEntity> implements CrudController<Dto> {

	protected CrudService<Dto, Entity> service;

	@Autowired
	@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
	public void setService(CrudService<Dto, Entity> service) {
		this.service = service;
	}

	@Override
	public QueryPageResult<Dto> query(Integer page,
									  Integer size,
									  Map<String, Object> criteria) {
		return service.queryPage(page, size, criteria);
	}

	@Override
	public List<Dto> list(Map<String, Object> criteria) {
		return service.listAll(criteria);
	}

	@Override
	public Dto get(Long id) {
		return service.get(id);
	}

	@Override
	public ApiResult save(Dto saveRequest) {
		try {
			final Dto dto = service.save(saveRequest);
			return ApiResult.of(GlobalErrorCode.SUCCESSFUL, dto);
		} catch (DataNotFoundException e) {
			return ApiResult.of(GlobalErrorCode.DATA_NOT_FOUND);
		}
	}

	@Override
	public ApiResult delete(String id) {
		String[] targets = id.split(",");
		Long[] ids = new Long[targets.length];
		for (int i = 0; i < targets.length; i++) {
			try {
				ids[i] = Long.parseLong(targets[i]);
			} catch (NumberFormatException e) {
				return ApiResult.of(GlobalErrorCode.ILLEGAL_REQUEST);
			}
		}
		service.deleteAll(ids);
		return ApiResult.of(GlobalErrorCode.SUCCESSFUL);
	}
}
